package cn.com.winning.ecare.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class HTTPGetTool {
	protected static DefaultHttpClient httpclient;
	private static HTTPGetTool tool = null;
	private String cookie = "";
	private static final int REQUEST_TIMEOUT = 45 * 1000;// 设置请求超时45秒钟
	private static final int SO_TIMEOUT = 45 * 1000; // 设置等待数据超时时间45秒钟
	private static final String CHARSET = HTTP.UTF_8;

//	private HTTPGetTool() {
//		BasicHttpParams httpParams = new BasicHttpParams();
//		HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
//		HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
//		httpclient = new DefaultHttpClient(httpParams);
//		// httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(),
//		// httpParams);
//	}
	
	private HTTPGetTool()
	{

	}

	public static synchronized HttpClient getHttpClient()
	{
		if (null == httpclient)
		{
			HttpParams params = new BasicHttpParams();
			// 设置一些基本参数
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, CHARSET);
			HttpProtocolParams.setUseExpectContinue(params, true);
			HttpProtocolParams.setUserAgent(params, "Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
					+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
			// 超时设置
			/* 从连接池中取连接的超时时间 */
			ConnManagerParams.setTimeout(params, SO_TIMEOUT);
			/* 连接超时 */
			HttpConnectionParams.setConnectionTimeout(params, REQUEST_TIMEOUT);
			/* 请求超时 */
			HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);

			// 设置我们的HttpClient支持HTTP和HTTPS两种模式
			SchemeRegistry schReg = new SchemeRegistry();
			schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
			schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

			// 使用线程安全的连接管理来创建HttpClient
			ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
			httpclient = new DefaultHttpClient(conMgr, params);
		}
		return httpclient;
	}

	public static HTTPGetTool getTool() {
		if (tool == null)
			tool = new HTTPGetTool();
		return tool;
		// return new HTTPGetTool();
	}

	public JSONObject login(String url) {
		HttpGet get = new HttpGet();
		try {
			if (url == null)
				return new JSONObject("{\"success\":false,\"msg\":\"未查到相关信息！\"}");
			
			get.setURI(new URI(url));
			HttpResponse response = getHttpClient().execute(get);
			int result = response.getStatusLine().getStatusCode();
			if (result == 200) {
				String strResult = EntityUtils.toString(response.getEntity(),
						HTTP.UTF_8);
				JSONObject json = new JSONObject(strResult);
				Header[] headers = response.getHeaders("Set-Cookie");
				if (headers.length != 0)
					cookie = headers[0].toString();
				get.abort();
				return json;
			} else
				get.abort();
				return new JSONObject("{\"success\":false,\"msg\":\"未查到相关信息！\"}");
		} catch (Exception e) {
			get.abort();
			e.printStackTrace();
			return null;
		}

	}

	public JSONObject post(String url, List<NameValuePair> parameters) {
		if (url == null)
			return null;
		HttpPost post = new HttpPost(url);
		try {
			
			post.setHeader("Cookie", cookie);
			if (parameters != null)
				post.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8));
			HttpResponse response = getHttpClient().execute(post);
			int result = response.getStatusLine().getStatusCode();
			Log.e("web", String.valueOf(result));
			if (result == 200) {
				String strResult = EntityUtils.toString(response.getEntity(),
						HTTP.UTF_8);
				Log.e("web", strResult);
				if (strResult.equals("no session"))
					return null;
				JSONObject json = new JSONObject(strResult);
				post.abort();
				return json;
			} else
				post.abort();
				return new JSONObject(
						"{\"success\":\"false\",\"msg\":\"未查到相关信息！\"}");

		} catch (Exception e) {
			e.printStackTrace();
			post.abort();
			return null;
		}
	}

	public JSONObject get(String url) {
		if (url == null)
			return null;
		HttpGet get = new HttpGet();
		try {
			
			get.setURI(new URI(url));
			get.setHeader("Cookie", cookie);
			HttpResponse response = getHttpClient().execute(get);
			int result = response.getStatusLine().getStatusCode();
			if (result == 200) {
				String strResult = EntityUtils.toString(response.getEntity(),
						HTTP.UTF_8);
				Log.e("web", strResult);
				if (strResult.equals("no session"))
					return null;
				JSONObject json = new JSONObject(strResult);
				get.abort();
				return json;
			} else {
				return null;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			get.abort();
			e.printStackTrace();
			return null;
		}
	}

	static public int checkResult(JSONObject json) {
		try {
			if (json == null || json.isNull("success"))
				return -1; // 错误，不成功
			String s = json.getString("success");
			if (s == null)
				return -1;
			if (s.equals("true"))
				return 0; // 成功
			if (s.equals(MSGUtils.NOSESSION))
				return 2; // 会话超时
			if (s.equals("false"))
				return 3; // 连接超时
			if (s.equals("norelust"))
				return 4;//
			else
				return 1;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1;
	}

	HttpResponse response1 = null;

	public JSONObject get1(String url) {
		if (url == null)
			return null;
		try {
			final HttpGet get = new HttpGet();
			get.setURI(new URI(url));
			get.setHeader("Cookie", cookie);

			// = httpclient.execute(get);
			Thread hth = new Thread() {
				@Override
				public void run() {
					try {
						response1 = getHttpClient().execute(get);
					} catch (IllegalArgumentException ec) {
						response1 = null;
						interrupted();
					} catch (ClientProtocolException e) {
						response1 = null;
						interrupted();
					} catch (IOException e) {
						response1 = null;
						interrupted();
					}
				}
			};
			hth.start();
			try {
				Thread.sleep(1000);
				if (response1 == null) {
					Thread.sleep(4000);
				}
				if (response1 == null) {
					hth.interrupt();
					return null;
				}

			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			int result = response1.getStatusLine().getStatusCode();
			if (result == 200) {
				String strResult = EntityUtils.toString(response1.getEntity(),
						HTTP.UTF_8);
				Log.e("web", strResult);
				if (strResult.equals("no session"))
					return null;
				JSONObject json = new JSONObject(strResult);
				return json;
			} else {
				return null;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public JSONObject post1(String url, List<NameValuePair> parameters) {
		response1 = null;
		if (url == null)
			return null;
		try {
			final HttpPost post = new HttpPost(url);
			post.setHeader("Cookie", cookie);
			post.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8));

			// = httpclient.execute(get);
			Thread hth = new Thread() {
				@Override
				public void run() {
					try {
						response1 = getHttpClient().execute(post);
					} catch (IllegalArgumentException ec) {
						response1 = null;
						interrupted();
					} catch (ClientProtocolException e) {
						response1 = null;
						interrupted();
					} catch (IOException e) {
						response1 = null;
						interrupted();
					}
				}
			};
			hth.start();
			try {
				Thread.sleep(1000);
				if (response1 == null) {
					Thread.sleep(40000);
				}
				if (response1 == null) {
					hth.interrupt();
					return null;
				}

			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			int result = response1.getStatusLine().getStatusCode();
			if (result == 200) {
				String strResult = EntityUtils.toString(response1.getEntity(),
						HTTP.UTF_8);
				Log.e("web", strResult);
				if (strResult.equals("no session"))
					return null;
				JSONObject json = new JSONObject(strResult);
				return json;
			} else
				return new JSONObject(
						"{\"success\":\"false\",\"msg\":\"未查到相关信息！\"}");
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	// 得到服务的传来的byte数组
	public Bitmap queryByteForPost(String url, List<NameValuePair> parameters) {
		try {
			HttpPost post = new HttpPost(url);
			post.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8));
			HttpResponse response = getHttpClient().execute(post);
			int result = response.getStatusLine().getStatusCode();
			if (result == 200) {

				InputStream in = response.getEntity().getContent();
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				byte[] buffer = new byte[256];
				int c = 0;
				while ((c = in.read(buffer)) != -1) {
					out.write(buffer, 0, c);
				}
				out.flush();
				buffer = out.toByteArray();
				out.close();
				in.close();
				Bitmap bitmap = BitmapFactory.decodeByteArray(buffer, 0,
						buffer.length);
				System.out.println(bitmap);
				// String str=new String(buffer);
				// System.out.println();
				return bitmap;
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
